/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * ReportFrame.java
 *
 * Created on 30 Mei 11, 10:29:29
 */
package log2excel;

import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.Rectangle;
import com.itextpdf.text.pdf.PdfDocument;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfWriter;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.GroupLayout;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JScrollPane;
import javax.swing.JTabbedPane;
import javax.swing.JTable;
import javax.swing.filechooser.FileNameExtensionFilter;
import javax.swing.table.DefaultTableModel;
import jxl.write.Font;
import jxl.write.WritableFont;
import log2excel.ExcelManager.CreateExcel;
import log2excel.ViewInterface.RowNumberTable;
import log2excel.ViewInterface.TableAccess;
import log2excel.model.ExtentionUsernameRecord;
import log2excel.model.HLRRecord;
import log2excel.model.OutgoingCallReport;
import log2excel.model.TrunkLineRecord;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.apache.poi.xwpf.usermodel.XWPFRun;
import org.apache.poi.xwpf.usermodel.XWPFTable;
import org.apache.poi.xwpf.usermodel.XWPFTableRow;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.JFreeChart;
import org.jfree.data.general.DefaultPieDataset;
import org.jfree.data.general.PieDataset;
import org.jfree.ui.action.ActionButton;

/**
 *
 * @author aegish
 */


public class ReportFrame extends javax.swing.JFrame {
    public static enum Option{
      ExtentionUsername,
      TrunkLine
    };
    private class ProcessedData{
        public long[] cost;
        public long[] duration;
        public long[] frequency;
        public double[] percentcost;
        public double[] percentduration;
        public double[] percentfrequency;

        public ProcessedData() {
            cost = new long[6];
            duration = new long[6];
            frequency = new long[6];
            percentcost = new double[6];
            percentduration = new double[6];
            percentfrequency = new double[6];
        }
    };
    private HashMap<Integer, ProcessedData> map;
    private Option option;
    private ArrayList arraylist;
    private long starttime;
    private long endttime;
    private long durtime;
    /** Creates new form ReportFrame */
    public ReportFrame(java.awt.Frame parent, boolean modal, Option opt,ArrayList selectedarray, long starttime, long endtime, long durtime) {
//        super(parent, modal);
        super("Report Summary");
        this.option = opt;
//        initComponents();
        this.starttime = starttime;
        this.endttime = endtime;
        this.durtime = durtime;
        map = new HashMap<Integer, ProcessedData>();
        for(int i = 0; i < selectedarray.size(); i++){
            map.put(i, new ProcessedData());
        }
        if (this.option == Option.ExtentionUsername){
            this.arraylist = new ArrayList<ExtentionUsernameRecord>(selectedarray);   
            prepareTabsExtUser();
            
        }
        else{
            this.arraylist = new ArrayList<TrunkLineRecord>(selectedarray);
            prepareTabsTrunkLine();
        }
        
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
    private void initComponents() {

        jTabbedPane1 = new javax.swing.JTabbedPane();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setName("Form"); // NOI18N

        jTabbedPane1.setName("jTabbedPane1"); // NOI18N

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jTabbedPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 400, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jTabbedPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 300, Short.MAX_VALUE)
        );

        pack();
    }// </editor-fold>                        

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                ReportFrame dialog = new ReportFrame(new javax.swing.JFrame(), true, ReportFrame.Option.ExtentionUsername, TableAccess.getExtentionUsernameRecords(), 0, 0, 0);
                dialog.addWindowListener(new java.awt.event.WindowAdapter() {

                    public void windowClosing(java.awt.event.WindowEvent e) {
                        System.exit(0);
                    }
                });
                dialog.setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify                     
    private javax.swing.JTabbedPane jTabbedPane1;
    // End of variables declaration
    
    private JTable alltable, costtable, durtable, freqtable, percentcosttable, percentdurtable, percentfreqtable;
    private void prepareTabsExtUser(){
        JTabbedPane tabs = new JTabbedPane();
        JButton previewBtn = new JButton("preview");
        JButton saveBtn = new ActionButton("save");
        alltable = new JTable(new  DefaultTableModel(new Object[][]{
        }, new String[]{
            "Extention",
            "Username",
            "Date",
            "Time",
            "Trunk",
            "Destination",
            "Location",
            "Duration",
            "Cost"
        })){

            @Override
            public boolean isCellEditable(int row, int column) {
                return false;
            }
            
        };
        tabs.add(makeTable(alltable, "All Report")); 
        
//        TODO : implement table
        DefaultTableModel model = (DefaultTableModel)alltable.getModel();
        ArrayList<OutgoingCallReport> callreportlist = getFilteredoutGoOutgoingCallReports(OutgoingCallReport.Records);
//        SimpleDateFormat df = new SimpleDateFormat("dd-MM-yyyy");
//        SimpleDateFormat tf = new SimpleDateFormat("HH:mm:ss");
        for (Iterator<OutgoingCallReport> it = callreportlist.iterator(); it.hasNext();) {
            OutgoingCallReport outgoingCallReport = it.next();
            model.addRow(populateAllReportRow(outgoingCallReport));
        }
        //        implement costtable
        costtable = new JTable(new DefaultTableModel(new Object[][]{}, new String[]{
            "Extention",
            "Username",
            "Local PSTN",
            "Local GSM",
            "SLJJ PTSN",
            "SLJJ GSM",
            "SLI",
            "Other",
            "Total"
        })){
            @Override
            public boolean isCellEditable(int row, int column) {
                return false;
            }
        };
        tabs.add(makeTable(costtable, "Sum Cost"));
        //fill costtable
        model = (DefaultTableModel)costtable.getModel();
        int index = 0;
        for (Iterator<ExtentionUsernameRecord> it = arraylist.iterator(); it.hasNext();) {
            ExtentionUsernameRecord usernameRecord = it.next();
            ProcessedData pd = map.get(index);
            
            model.addRow(new String[]{
                usernameRecord.Extention,
                usernameRecord.Username,
                ""+pd.cost[0],
                ""+pd.cost[1],
                ""+pd.cost[2],
                ""+pd.cost[3],
                ""+pd.cost[4],
                ""+pd.cost[5],
                ""+(pd.cost[0] +
                    pd.cost[1] +
                    pd.cost[2] +
                    pd.cost[3] +
                    pd.cost[4] +
                    pd.cost[5])
            });
            index++;
        }
//        implement freqtable
        durtable = new JTable(new DefaultTableModel(new Object[][]{}, new String[]{
            "Extention",
            "Username",
            "Local PSTN",
            "Local GSM",
            "SLJJ PTSN",
            "SLJJ GSM",
            "SLI",
            "Other",
            "Total"
        })){
            @Override
            public boolean isCellEditable(int row, int column) {
                return false;
            }
        };
        tabs.add(makeTable(durtable, "Sum Duration"));
        //fill freqtable
        model = (DefaultTableModel)durtable.getModel();
        index = 0;
        for (Iterator<ExtentionUsernameRecord> it = arraylist.iterator(); it.hasNext();) {
            ExtentionUsernameRecord usernameRecord = it.next();
            ProcessedData pd = map.get(index++);
            model.addRow(new String[]{
                usernameRecord.Extention,
                usernameRecord.Username,
                ""+pd.duration[0],
                ""+pd.duration[1],
                ""+pd.duration[2],
                ""+pd.duration[3],
                ""+pd.duration[4],
                ""+pd.duration[5],
                ""+(pd.duration[0] +
                    pd.duration[1] +
                    pd.duration[2] +
                    pd.duration[3] +
                    pd.duration[4] +
                    pd.duration[5])
            });
        }
//        implement freqtable
        freqtable = new JTable(new DefaultTableModel(new Object[][]{}, new String[]{
            "Extention",
            "Username",
            "Local PSTN",
            "Local GSM",
            "SLJJ PTSN",
            "SLJJ GSM",
            "SLI",
            "Other",
            "Total"
        })){
            @Override
            public boolean isCellEditable(int row, int column) {
                return false;
            }
        };
        tabs.add(makeTable(freqtable, "Sum Frequency"));
        //fill freqtable
        model = (DefaultTableModel)freqtable.getModel();
        index = 0;
        for (Iterator<ExtentionUsernameRecord> it = arraylist.iterator(); it.hasNext();) {
            ExtentionUsernameRecord usernameRecord = it.next();
            ProcessedData pd = map.get(index++);
            model.addRow(new String[]{
                usernameRecord.Extention,
                usernameRecord.Username,
                ""+pd.frequency[0],
                ""+pd.frequency[1],
                ""+pd.frequency[2],
                ""+pd.frequency[3],
                ""+pd.frequency[4],
                ""+pd.frequency[5],
                ""+(pd.frequency[0] + 
                    pd.frequency[1] + 
                    pd.frequency[2] + 
                    pd.frequency[3] + 
                    pd.frequency[4] + 
                    pd.frequency[5])
            });
        }
//        implement percentcosttable
        percentcosttable = new JTable(new DefaultTableModel(new Object[][]{}, new String[]{
            "Extention",
            "Username",
            "Local PSTN",
            "Local GSM",
            "SLJJ PTSN",
            "SLJJ GSM",
            "SLI",
            "Other",
            "Total"
        })){
            @Override
            public boolean isCellEditable(int row, int column) {
                return false;
            }
        };
        tabs.add(makeTable(percentcosttable, "% Cost"));
        //fill percentcosttable
        model = (DefaultTableModel)percentcosttable.getModel();
        index = 0;
        for (Iterator<ExtentionUsernameRecord> it = arraylist.iterator(); it.hasNext();) {
            ExtentionUsernameRecord usernameRecord = it.next();
            ProcessedData pd = map.get(index++);
            double total = pd.cost[0] + pd.cost[1] +pd.cost[2] +pd.cost[3] +pd.cost[4] +pd.cost[5];
            if (total > 0)
            model.addRow(new String[]{
                usernameRecord.Extention,
                usernameRecord.Username,
                ""+(pd.cost[0]*100)/ total,
                ""+(pd.cost[1]*100)/ total,
                ""+(pd.cost[2]*100)/ total,
                ""+(pd.cost[3]*100)/ total,
                ""+(pd.cost[4]*100)/ total,
                ""+(pd.cost[5]*100)/ total,
                "100"
            });
        }
//        implement percentdurtable
        percentdurtable = new JTable(new DefaultTableModel(new Object[][]{}, new String[]{
            "Extention",
            "Username",
            "Local PSTN",
            "Local GSM",
            "SLJJ PTSN",
            "SLJJ GSM",
            "SLI",
            "Other",
            "Total"
        })){
            @Override
            public boolean isCellEditable(int row, int column) {
                return false;
            }
        };
        tabs.add(makeTable(percentdurtable, "% Duration"));
        //fill percentduration table
        model = (DefaultTableModel)percentdurtable.getModel();
        index = 0;
        for (Iterator<ExtentionUsernameRecord> it = arraylist.iterator(); it.hasNext();) {
            ExtentionUsernameRecord usernameRecord = it.next();
            ProcessedData pd = map.get(index++);
            double total = pd.duration[0] + pd.duration[1] +pd.duration[2] +pd.duration[3] +pd.duration[4] +pd.duration[5];
            if (total > 0)
            model.addRow(new String[]{
                usernameRecord.Extention,
                usernameRecord.Username,
                ""+(pd.duration[0] * 100)/total,
                ""+(pd.duration[1] * 100)/total,
                ""+(pd.duration[2] * 100)/total,
                ""+(pd.duration[3] * 100)/total,
                ""+(pd.duration[4] * 100)/total,
                ""+(pd.duration[5] * 100)/total,
                "100"
            });
        }
//        implement percentfreqtable
        percentfreqtable = new JTable(new DefaultTableModel(new Object[][]{}, new String[]{
            "Extention",
            "Username",
            "Local PSTN",
            "Local GSM",
            "SLJJ PTSN",
            "SLJJ GSM",
            "SLI",
            "Other",
            "Total"
        })){
            @Override
            public boolean isCellEditable(int row, int column) {
                return false;
            }
        };
        tabs.add(makeTable(percentfreqtable, "% Frequency"));
        //fill percentfreqtable
        model = (DefaultTableModel)percentfreqtable.getModel();
        index = 0;
        for (Iterator<ExtentionUsernameRecord> it = arraylist.iterator(); it.hasNext();) {
            ExtentionUsernameRecord usernameRecord = it.next();
            ProcessedData pd = map.get(index++);
            double total = pd.frequency[0] + pd.frequency[1] +pd.frequency[2] +pd.frequency[3] +pd.frequency[4] +pd.frequency[5];
            if (total > 0)
            model.addRow(new String[]{
                usernameRecord.Extention,
                usernameRecord.Username,
                ""+(pd.frequency[0] * 100)/total,
                ""+(pd.frequency[1] * 100)/total,
                ""+(pd.frequency[2] * 100)/total,
                ""+(pd.frequency[3] * 100)/total,
                ""+(pd.frequency[4] * 100)/total,
                ""+(pd.frequency[5] * 100)/total,
                "100"
                
            });
        }
        saveBtn.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent e) {
                SaveReport();
            }
        });
        
        GroupLayout layout = new GroupLayout(this.getContentPane());
        layout.setAutoCreateGaps(true);
        layout.setHorizontalGroup(layout.createParallelGroup()
                .addComponent(tabs)
                .addGroup(layout.createSequentialGroup()
                    .addComponent(previewBtn)
                    .addComponent(saveBtn)));
        layout.setVerticalGroup(layout.createSequentialGroup()
                .addComponent(tabs)
                .addGroup(layout.createParallelGroup(GroupLayout.Alignment.CENTER)
                    .addComponent(previewBtn)
                    .addComponent(saveBtn)));
        this.getContentPane().setLayout(layout);
        pack();
    }
    private void prepareTabsTrunkLine(){
        JTabbedPane tabs = new JTabbedPane();
        JButton previewBtn = new JButton("preview");
        JButton saveBtn = new ActionButton("save");
//        implement alltable
        alltable = new JTable(new  DefaultTableModel(new Object[][]{}, new String[]{
            "Trunk",
            "Line",
            "Date",
            "Time",
            "Destination",
            "Location",
            "Duration",
            "Cost"
        })){
            @Override
            public boolean isCellEditable(int row, int column) {
                return false;
            }
        };
        tabs.add(makeTable(alltable, "All Report"));
//        fill alltable
        DefaultTableModel model = (DefaultTableModel)alltable.getModel();
        ArrayList<OutgoingCallReport> callreportlist = getFilteredoutGoOutgoingCallReports(OutgoingCallReport.Records);
        
        for (Iterator<OutgoingCallReport> it = callreportlist.iterator(); it.hasNext();) {
            OutgoingCallReport outgoingCallReport = it.next();
            model.addRow(populateAllReportRow(outgoingCallReport));
        }
//        implement costtable
        costtable = new JTable(new DefaultTableModel(new Object[][]{}, new String[]{
            "Trunk",
            "Line",
            "Local PSTN",
            "Local GSM",
            "SLJJ PTSN",
            "SLJJ GSM",
            "SLI",
            "Other",
            "Total"
        })){
            @Override
            public boolean isCellEditable(int row, int column) {
                return false;
            }
        };
        tabs.add(makeTable(costtable, "Sum Cost"));
        //fill costtable
        model = (DefaultTableModel)costtable.getModel();
        int index = 0;
        for (Iterator<TrunkLineRecord> it = arraylist.iterator(); it.hasNext();) {
            TrunkLineRecord trunklineRecord = it.next();
            ProcessedData pd = map.get(index);
            
            model.addRow(new String[]{
                trunklineRecord.Trunk,
                trunklineRecord.Line,
                ""+pd.cost[0],
                ""+pd.cost[1],
                ""+pd.cost[2],
                ""+pd.cost[3],
                ""+pd.cost[4],
                ""+pd.cost[5],
                ""+(pd.cost[0] +
                    pd.cost[1] +
                    pd.cost[2] +
                    pd.cost[3] +
                    pd.cost[4] +
                    pd.cost[5])
            });
            index++;
        }
//        implement freqtable
        durtable = new JTable(new DefaultTableModel(new Object[][]{}, new String[]{
            "Trunk",
            "Line",
            "Local PSTN",
            "Local GSM",
            "SLJJ PTSN",
            "SLJJ GSM",
            "SLI",
            "Other",
            "Total"
        })){
            @Override
            public boolean isCellEditable(int row, int column) {
                return false;
            }
        };
        tabs.add(makeTable(durtable, "Sum Frequency"));
        //fill durtable
        model = (DefaultTableModel)durtable.getModel();
        index = 0;
        for (Iterator<TrunkLineRecord> it = arraylist.iterator(); it.hasNext();) {
            TrunkLineRecord trunklineRecord = it.next();
            ProcessedData pd = map.get(index);
            
            model.addRow(new String[]{
                trunklineRecord.Trunk,
                trunklineRecord.Line,
                ""+pd.duration[0],
                ""+pd.duration[1],
                ""+pd.duration[2],
                ""+pd.duration[3],
                ""+pd.duration[4],
                ""+pd.duration[5],
                ""+(pd.duration[0] +
                    pd.duration[1] +
                    pd.duration[2] +
                    pd.duration[3] +
                    pd.duration[4] +
                    pd.duration[5])
            });
            index++;
        }
//        implement freqtable
        freqtable = new JTable(new DefaultTableModel(new Object[][]{}, new String[]{
            "Trunk",
            "Line",
            "Local PSTN",
            "Local GSM",
            "SLJJ PTSN",
            "SLJJ GSM",
            "SLI",
            "Other",
            "Total"
        })){
            @Override
            public boolean isCellEditable(int row, int column) {
                return false;
            }
        };
        tabs.add(makeTable(freqtable, "Sum Frequency"));
        //fill durtable
        model = (DefaultTableModel)freqtable.getModel();
        index = 0;
        for (Iterator<TrunkLineRecord> it = arraylist.iterator(); it.hasNext();) {
            TrunkLineRecord trunklineRecord = it.next();
            ProcessedData pd = map.get(index);
            
            model.addRow(new String[]{
                trunklineRecord.Trunk,
                trunklineRecord.Line,
                ""+pd.frequency[0],
                ""+pd.frequency[1],
                ""+pd.frequency[2],
                ""+pd.frequency[3],
                ""+pd.frequency[4],
                ""+pd.frequency[5],
                ""+(pd.frequency[0] +
                    pd.frequency[1] +
                    pd.frequency[2] +
                    pd.frequency[3] +
                    pd.frequency[4] +
                    pd.frequency[5])
            });
            index++;
        }
//        implement costtable
        percentcosttable = new JTable(new DefaultTableModel(new Object[][]{}, new String[]{
            "Trunk",
            "Line",
            "Local PSTN",
            "Local GSM",
            "SLJJ PTSN",
            "SLJJ GSM",
            "SLI",
            "Other",
            "Total"
        })){
            @Override
            public boolean isCellEditable(int row, int column) {
                return false;
            }
        };
        tabs.add(makeTable(percentcosttable, "% Cost"));
        //fill percentcosttable
        model = (DefaultTableModel)percentcosttable.getModel();
        index = 0;
        for (Iterator<TrunkLineRecord> it = arraylist.iterator(); it.hasNext();) {
            TrunkLineRecord trunklineRecord = it.next();
            ProcessedData pd = map.get(index++);
            double total = pd.cost[0] + pd.cost[1] +pd.cost[2] +pd.cost[3] +pd.cost[4] +pd.cost[5];
//            double total_100 = total / 100;
            if (total > 0)
            model.addRow(new String[]{
                trunklineRecord.Trunk,
                trunklineRecord.Line,
                ""+(pd.cost[0]*100)/ total,
                ""+(pd.cost[1]*100)/ total,
                ""+(pd.cost[2]*100)/ total,
                ""+(pd.cost[3]*100)/ total,
                ""+(pd.cost[4]*100)/ total,
                ""+(pd.cost[5]*100)/ total,
                "100"
            });
        }
//        implement freqtable
        percentdurtable = new JTable(new DefaultTableModel(new Object[][]{}, new String[]{
            "Trunk",
            "Line",
            "Local PSTN",
            "Local GSM",
            "SLJJ PTSN",
            "SLJJ GSM",
            "SLI",
            "Other",
            "Total"
        })){
            @Override
            public boolean isCellEditable(int row, int column) {
                return false;
            }
        };
        tabs.add(makeTable(percentdurtable, "% Duration"));
        //fill percentcosttable
        model = (DefaultTableModel)percentdurtable.getModel();
        index = 0;
        for (Iterator<TrunkLineRecord> it = arraylist.iterator(); it.hasNext();) {
            TrunkLineRecord trunklineRecord = it.next();
            ProcessedData pd = map.get(index++);
            double total = pd.duration[0] + pd.duration[1] +pd.duration[2] +pd.duration[3] +pd.duration[4] +pd.duration[5];
//            double total_100 = total / 100;
            if (total > 0)
            model.addRow(new String[]{
                trunklineRecord.Trunk,
                trunklineRecord.Line,
                ""+(pd.duration[0]*100)/ total,
                ""+(pd.duration[1]*100)/ total,
                ""+(pd.duration[2]*100)/ total,
                ""+(pd.duration[3]*100)/ total,
                ""+(pd.duration[4]*100)/ total,
                ""+(pd.duration[5]*100)/ total,
                "100"
            });
        }
//        implement freqtable
        percentfreqtable = new JTable(new DefaultTableModel(new Object[][]{}, new String[]{
            "Trunk",
            "Line",
            "Local PSTN",
            "Local GSM",
            "SLJJ PTSN",
            "SLJJ GSM",
            "SLI",
            "Other",
            "Total"
        })){
            @Override
            public boolean isCellEditable(int row, int column) {
                return false;
            }
        };
        tabs.add(makeTable(percentfreqtable, "% Frequency"));
        //fill percentcosttable
        model = (DefaultTableModel)percentfreqtable.getModel();
        index = 0;
        for (Iterator<TrunkLineRecord> it = arraylist.iterator(); it.hasNext();) {
            TrunkLineRecord trunklineRecord = it.next();
            ProcessedData pd = map.get(index++);
            double total = pd.frequency[0] + pd.frequency[1] +pd.frequency[2] +pd.frequency[3] +pd.frequency[4] +pd.frequency[5];
//            double total_100 = total / 100;
            if (total > 0)
            model.addRow(new String[]{
                trunklineRecord.Trunk,
                trunklineRecord.Line,
                ""+(pd.frequency[0]*100)/ total,
                ""+(pd.frequency[1]*100)/ total,
                ""+(pd.frequency[2]*100)/ total,
                ""+(pd.frequency[3]*100)/ total,
                ""+(pd.frequency[4]*100)/ total,
                ""+(pd.frequency[5]*100)/ total,
                "100"
            });
        }
        saveBtn.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent e) {
                SaveReport();
            }
        });
        previewBtn.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
////                Sum Cost"Local PSTN",
////            "Local GSM",
////            "SLJJ PTSN",
////            "SLJJ GSM",
////            "SLI",
////            "Other",
//                DefaultPieDataset dataset = new DefaultPieDataset();
//                long[] total = new long[6]; 
//                for (int i = 0; i < arraylist.size(); i++){
//                    ProcessedData pd = map.get(i);
//                    total[0] += pd.cost[0];
//                    total[1] += pd.cost[1];
//                    total[2] += pd.cost[2];
//                    total[3] += pd.cost[3];
//                    total[4] += pd.cost[4];
//                    total[5] += pd.cost[5];
//                }
//                dataset.setValue("Local PSTN", total[0]);
//                dataset.setValue("Local GSM", total[1]);
//                dataset.setValue("SLJJ PSTN", total[2]);
//                dataset.setValue("SLJJ GSM", total[3]);
//                dataset.setValue("SLI", total[4]);
//                dataset.setValue("other", total[5]);
//                JFreeChart chart = ChartFactory.createPieChart("Sum Cost", dataset, true, true, true);
//                JFrame chartFrame = new JFrame("Chart");
            }
        });
        GroupLayout layout = new GroupLayout(this.getContentPane());
        layout.setAutoCreateGaps(true);
        layout.setHorizontalGroup(layout.createParallelGroup()
                .addComponent(tabs)
                .addGroup(layout.createSequentialGroup()
                    .addComponent(previewBtn)
                    .addComponent(saveBtn)));
        layout.setVerticalGroup(layout.createSequentialGroup()
                .addComponent(tabs)
                .addGroup(layout.createParallelGroup(GroupLayout.Alignment.CENTER)
                    .addComponent(previewBtn)
                    .addComponent(saveBtn)));
        this.getContentPane().setLayout(layout);
        pack();
    }
    private String selectedSaveExtention;
    private void SaveReport(){
        JFileChooser chooser = new JFileChooser();
        chooser.setAcceptAllFileFilterUsed(false);
        chooser.addChoosableFileFilter(new FileNameExtensionFilter("Pdf document", "pdf"));
        chooser.addChoosableFileFilter(new FileNameExtensionFilter("Word 2007 document", "docx"));
        chooser.addChoosableFileFilter(new FileNameExtensionFilter("Excel 2007 document", "xlsx"));
        chooser.addChoosableFileFilter(new FileNameExtensionFilter("Excel 2003 document", "xls"));
        selectedSaveExtention = ".xls";
        chooser.addPropertyChangeListener(JFileChooser.FILE_FILTER_CHANGED_PROPERTY, new PropertyChangeListener() {
            public void propertyChange(PropertyChangeEvent evt) {
                selectedSaveExtention = "."+((FileNameExtensionFilter)evt.getNewValue()).getExtensions()[0];
            }
        });
        String filename;
        if(chooser.showSaveDialog(ReportFrame.this) == JFileChooser.APPROVE_OPTION){
            filename = chooser.getSelectedFile().getAbsolutePath();
            if (!filename.endsWith(selectedSaveExtention))
                filename += selectedSaveExtention;
            if (selectedSaveExtention.equals(".xls"))
            {
                saveToXls(filename);
            }
            else if (selectedSaveExtention.equals(".xlsx")){
                saveToXlsx(filename);
            }
            else if (selectedSaveExtention.equals(".docx")){
                saveToDocx(filename);
            }
            else if (selectedSaveExtention.equals(".pdf")){
                saveToPdf(filename);
            }
        }
    }
    private void saveToXls(String filename){
        CreateExcel ce = new CreateExcel(filename);
        // All Report
        ce.createSheet("All Report", 0);
        ArrayList<String> row = new ArrayList<String>();
        int rowcount = alltable.getRowCount();
        int colcount = alltable.getColumnCount();
        row.add("No.");
        for (int i = 0; i < colcount; i++){
            row.add(alltable.getColumnName(i));
        }
        ce.putRow(0, 0, row, new WritableFont(Font.ARIAL), null);
        row.clear();
        for (int i  = 0; i < rowcount; i++){
            row.add(""+(i+1));
            for (int j = 0; j < colcount; j++){
                row.add(alltable.getValueAt(i, j).toString());
            }
            ce.putRow(i+1, 0, row, new WritableFont(Font.ARIAL), null);
            row.clear();
        }
//                    Sum Cost
        ce.createSheet("Sum Cost", 1);
        row = new ArrayList<String>();
        rowcount = costtable.getRowCount();
        colcount = costtable.getColumnCount();
        row.add("No.");
        for (int i = 0; i < colcount; i++){
            row.add(costtable.getColumnName(i));
        }
        ce.putRow(0, 0, row, new WritableFont(Font.ARIAL), null);
        row.clear();
        for (int i  = 0; i < rowcount; i++){
            row.add(""+(i+1));
            for (int j = 0; j < colcount; j++){
                row.add(costtable.getValueAt(i, j).toString());
            }
            ce.putRow(i+1, 0, row, new WritableFont(Font.ARIAL), null);
            row.clear();
        }
//                    Sum Duration
        ce.createSheet("Sum Duration", 2);
        row = new ArrayList<String>();
        rowcount = durtable.getRowCount();
        colcount = durtable.getColumnCount();
        row.add("No.");
        for (int i = 0; i < colcount; i++){
            row.add(durtable.getColumnName(i));
        }
        ce.putRow(0, 0, row, new WritableFont(Font.ARIAL), null);
        row.clear();
        for (int i  = 0; i < rowcount; i++){
            row.add(""+(i+1));
            for (int j = 0; j < colcount; j++){
                row.add(durtable.getValueAt(i, j).toString());
            }
            ce.putRow(i+1, 0, row, new WritableFont(Font.ARIAL), null);
            row.clear();
        }
//                    Sum Frequency
        ce.createSheet("Sum Frequency", 3);
        row = new ArrayList<String>();
        rowcount = freqtable.getRowCount();
        colcount = freqtable.getColumnCount();
        row.add("No.");
        for (int i = 0; i < colcount; i++){
            row.add(freqtable.getColumnName(i));
        }
        ce.putRow(0, 0, row, new WritableFont(Font.ARIAL), null);
        row.clear();
        for (int i  = 0; i < rowcount; i++){
            row.add(""+(i+1));
            for (int j = 0; j < colcount; j++){
                row.add(freqtable.getValueAt(i, j).toString());
            }
            ce.putRow(i+1, 0, row, new WritableFont(Font.ARIAL), null);
            row.clear();
        }
//                    Percentage Cost
        ce.createSheet("Percentage Cost", 4);
        row = new ArrayList<String>();
        rowcount = percentcosttable.getRowCount();
        colcount = percentcosttable.getColumnCount();
        row.add("No.");
        for (int i = 0; i < colcount; i++){
            row.add(percentcosttable.getColumnName(i));
        }
        ce.putRow(0, 0, row, new WritableFont(Font.ARIAL), null);
        row.clear();
        for (int i  = 0; i < rowcount; i++){
            row.add(""+(i+1));
            for (int j = 0; j < colcount; j++){
                row.add(percentcosttable.getValueAt(i, j).toString());
            }
            ce.putRow(i+1, 0, row, new WritableFont(Font.ARIAL), null);
            row.clear();
        }
//                    Percentage Duration
        ce.createSheet("Percentage Duration", 5);
        row = new ArrayList<String>();
        rowcount = percentdurtable.getRowCount();
        colcount = percentdurtable.getColumnCount();
        row.add("No.");
        for (int i = 0; i < colcount; i++){
            row.add(percentdurtable.getColumnName(i));
        }
        ce.putRow(0, 0, row, new WritableFont(Font.ARIAL), null);
        row.clear();
        for (int i  = 0; i < rowcount; i++){
            row.add(""+(i+1));
            for (int j = 0; j < colcount; j++){
                row.add(percentdurtable.getValueAt(i, j).toString());
            }
            ce.putRow(i+1, 0, row, new WritableFont(Font.ARIAL), null);
            row.clear();
        }
//                    Percentage Frequency
        ce.createSheet("Percentage Frequency", 6);
        row = new ArrayList<String>();
        rowcount = percentfreqtable.getRowCount();
        colcount = percentfreqtable.getColumnCount();
        row.add("No.");
        for (int i = 0; i < colcount; i++){
            row.add(percentfreqtable.getColumnName(i));
        }
        ce.putRow(0, 0, row, new WritableFont(Font.ARIAL), null);
        row.clear();
        for (int i  = 0; i < rowcount; i++){
            row.add(""+(i+1));
            for (int j = 0; j < colcount; j++){
                row.add(percentfreqtable.getValueAt(i, j).toString());
            }
            ce.putRow(i+1, 0, row, new WritableFont(Font.ARIAL), null);
            row.clear();
        }
//                    save file excel
        ce.write_close();
    }
    private void saveToXlsx(String filename){
        XSSFWorkbook workbook = new XSSFWorkbook();
        XSSFSheet allSheet = workbook.createSheet("all Report");
        XSSFSheet costSheet = workbook.createSheet("Cost Summary");
        XSSFSheet durSheet = workbook.createSheet("Duration Summary");
        XSSFSheet freqSheet = workbook.createSheet("Frequency Summary");
        XSSFSheet pcostSheet = workbook.createSheet("Percentage Cost Summary");
        XSSFSheet pdurSheet = workbook.createSheet("Percentage Duration Summary");
        XSSFSheet pfreqSheet = workbook.createSheet("Percentage Frequency Summary");
        ArrayList<String> row = new ArrayList<String>();
        
//        all Report
        int rowcount = alltable.getRowCount();
        int colcount = alltable.getColumnCount();
        XSSFRow rowexcel = allSheet.createRow(0);
        int index = 0;
        row.add("No.");
        for (int i = 0; i < colcount; i++){
            row.add(alltable.getColumnName(i));
        }
        for (Iterator<String> it = row.iterator(); it.hasNext();) {
            String string = it.next();
            rowexcel.createCell(index++).setCellValue(string);
        }
        index = 0;
        row.clear();
        for (int i  = 0; i < rowcount; i++){
            row.add(""+(i+1));
            for (int j = 0; j < colcount; j++){
                row.add(alltable.getValueAt(i, j).toString());
            }
            rowexcel = allSheet.createRow(i+1);
            for (Iterator<String> it = row.iterator(); it.hasNext();) {
                String string = it.next();
                rowexcel.createCell(index++).setCellValue(string);
            }
            index = 0;
            row.clear();
        }
        
//        Cost Sum
        rowcount = costtable.getRowCount();
        colcount = costtable.getColumnCount();
        rowexcel = costSheet.createRow(0);
        index = 0;
        row.add("No.");
        for (int i = 0; i < colcount; i++){
            row.add(costtable.getColumnName(i));
        }
        for (Iterator<String> it = row.iterator(); it.hasNext();) {
            String string = it.next();
            rowexcel.createCell(index++).setCellValue(string);
        }
        index = 0;
        row.clear();
        for (int i  = 0; i < rowcount; i++){
            row.add(""+(i+1));
            for (int j = 0; j < colcount; j++){
                row.add(costtable.getValueAt(i, j).toString());
            }
            rowexcel = costSheet.createRow(i+1);
            for (Iterator<String> it = row.iterator(); it.hasNext();) {
                String string = it.next();
                rowexcel.createCell(index++).setCellValue(string);
            }
            index = 0;
            row.clear();
        }
        
//        Duration Sum
        rowcount = durtable.getRowCount();
        colcount = durtable.getColumnCount();
        rowexcel = durSheet.createRow(0);
        index = 0;
        row.add("No.");
        for (int i = 0; i < colcount; i++){
            row.add(durtable.getColumnName(i));
        }
        for (Iterator<String> it = row.iterator(); it.hasNext();) {
            String string = it.next();
            rowexcel.createCell(index++).setCellValue(string);
        }
        index = 0;
        row.clear();
        for (int i  = 0; i < rowcount; i++){
            row.add(""+(i+1));
            for (int j = 0; j < colcount; j++){
                row.add(durtable.getValueAt(i, j).toString());
            }
            rowexcel = durSheet.createRow(i+1);
            for (Iterator<String> it = row.iterator(); it.hasNext();) {
                String string = it.next();
                rowexcel.createCell(index++).setCellValue(string);
            }
            index = 0;
            row.clear();
        }
        
//        Frequency Sum
        rowcount = freqtable.getRowCount();
        colcount = freqtable.getColumnCount();
        rowexcel = freqSheet.createRow(0);
        index = 0;
        row.add("No.");
        for (int i = 0; i < colcount; i++){
            row.add(freqtable.getColumnName(i));
        }
        for (Iterator<String> it = row.iterator(); it.hasNext();) {
            String string = it.next();
            rowexcel.createCell(index++).setCellValue(string);
        }
        index = 0;
        row.clear();
        for (int i  = 0; i < rowcount; i++){
            row.add(""+(i+1));
            for (int j = 0; j < colcount; j++){
                row.add(freqtable.getValueAt(i, j).toString());
            }
            rowexcel = freqSheet.createRow(i+1);
            for (Iterator<String> it = row.iterator(); it.hasNext();) {
                String string = it.next();
                rowexcel.createCell(index++).setCellValue(string);
            }
            index = 0;
            row.clear();
        }
        
//        Percentage Cost Sum
        rowcount = percentcosttable.getRowCount();
        colcount = percentcosttable.getColumnCount();
        rowexcel = pcostSheet.createRow(0);
        index = 0;
        row.add("No.");
        for (int i = 0; i < colcount; i++){
            row.add(percentcosttable.getColumnName(i));
        }
        for (Iterator<String> it = row.iterator(); it.hasNext();) {
            String string = it.next();
            rowexcel.createCell(index++).setCellValue(string);
        }
        index = 0;
        row.clear();
        for (int i  = 0; i < rowcount; i++){
            row.add(""+(i+1));
            for (int j = 0; j < colcount; j++){
                row.add(percentcosttable.getValueAt(i, j).toString());
            }
            rowexcel = pcostSheet.createRow(i+1);
            for (Iterator<String> it = row.iterator(); it.hasNext();) {
                String string = it.next();
                rowexcel.createCell(index++).setCellValue(string);
            }
            index = 0;
            row.clear();
        }
        
//        Percentage Duration Sum
        rowcount = percentdurtable.getRowCount();
        colcount = percentdurtable.getColumnCount();
        rowexcel = pdurSheet.createRow(0);
        index = 0;
        row.add("No.");
        for (int i = 0; i < colcount; i++){
            row.add(percentdurtable.getColumnName(i));
        }
        for (Iterator<String> it = row.iterator(); it.hasNext();) {
            String string = it.next();
            rowexcel.createCell(index++).setCellValue(string);
        }
        index = 0;
        row.clear();
        for (int i  = 0; i < rowcount; i++){
            row.add(""+(i+1));
            for (int j = 0; j < colcount; j++){
                row.add(percentdurtable.getValueAt(i, j).toString());
            }
            rowexcel = pdurSheet.createRow(i+1);
            for (Iterator<String> it = row.iterator(); it.hasNext();) {
                String string = it.next();
                rowexcel.createCell(index++).setCellValue(string);
            }
            index = 0;
            row.clear();
        }
        
//        Percentage Frequency Sum
        rowcount = percentfreqtable.getRowCount();
        colcount = percentfreqtable.getColumnCount();
        rowexcel = pfreqSheet.createRow(0);
        index = 0;
        row.add("No.");
        for (int i = 0; i < colcount; i++){
            row.add(percentfreqtable.getColumnName(i));
        }
        for (Iterator<String> it = row.iterator(); it.hasNext();) {
            String string = it.next();
            rowexcel.createCell(index++).setCellValue(string);
        }
        index = 0;
        row.clear();
        for (int i  = 0; i < rowcount; i++){
            row.add(""+(i+1));
            for (int j = 0; j < colcount; j++){
                row.add(percentfreqtable.getValueAt(i, j).toString());
            }
            rowexcel = pfreqSheet.createRow(i+1);
            for (Iterator<String> it = row.iterator(); it.hasNext();) {
                String string = it.next();
                rowexcel.createCell(index++).setCellValue(string);
            }
            index = 0;
            row.clear();
        }
        
        FileOutputStream outputStream = null;
        try {
            outputStream = new FileOutputStream(filename);
        } catch (FileNotFoundException ex) {
            Logger.getLogger(ReportFrame.class.getName()).log(Level.SEVERE, null, ex);
        }
        try {
            workbook.write(outputStream);
            outputStream.close();
        } catch (IOException ex) {
            Logger.getLogger(ReportFrame.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    private void saveToDocx(String filename){
        XWPFDocument document = new XWPFDocument();
        XWPFParagraph paragraph1 = document.createParagraph();
        XWPFRun paragraph1run = paragraph1.createRun();
        XWPFTable table;
        XWPFTableRow rowtable;
//        XWPFTableRow rowtable = table.createRow();
        ArrayList<String> row = new ArrayList<String>();
        
        //        all Report
        paragraph1run.setText("All Report");
        int rowcount = alltable.getRowCount();
        int colcount = alltable.getColumnCount();
        table = document.createTable(1, colcount + 1);
        rowtable = table.getRow(0);
        int index = 0;
        row.add("No.");
        for (int i = 0; i < colcount; i++){
            row.add(alltable.getColumnName(i));
        }
        for (Iterator<String> it = row.iterator(); it.hasNext();) {
            String string = it.next();
            rowtable.getCell(index++).setText(string);
        }
        index = 0;
        row.clear();
        for (int i  = 0; i < rowcount; i++){
            row.add(""+(i+1));
            for (int j = 0; j < colcount; j++){
                row.add(alltable.getValueAt(i, j).toString());
            }
            rowtable = table.createRow();
            for (Iterator<String> it = row.iterator(); it.hasNext();) {
                String string = it.next();
                rowtable.getCell(index++).setText(string);
            }
            index = 0;
            row.clear();
        }
        
//        Cost Summary
        paragraph1 = document.createParagraph();
        paragraph1run = paragraph1.createRun();
        paragraph1run.addBreak();
        paragraph1run.setText("Cost Summary");
        rowcount = costtable.getRowCount();
        colcount = costtable.getColumnCount();
        table = document.createTable(1, colcount + 1);
        rowtable = table.getRow(0);
        index = 0;
        row.add("No.");
        for (int i = 0; i < colcount; i++){
            row.add(costtable.getColumnName(i));
        }
        for (Iterator<String> it = row.iterator(); it.hasNext();) {
            String string = it.next();
            rowtable.getCell(index++).setText(string);
        }
        index = 0;
        row.clear();
        for (int i  = 0; i < rowcount; i++){
            row.add(""+(i+1));
            for (int j = 0; j < colcount; j++){
                row.add(costtable.getValueAt(i, j).toString());
            }
            rowtable = table.createRow();
            for (Iterator<String> it = row.iterator(); it.hasNext();) {
                String string = it.next();
                rowtable.getCell(index++).setText(string);
            }
            index = 0;
            row.clear();
        }
        
//        Duration Summary
        paragraph1 = document.createParagraph();
        paragraph1run = paragraph1.createRun();
        paragraph1run.addBreak();
        paragraph1run.setText("Duration Summary");
        rowcount = durtable.getRowCount();
        colcount = durtable.getColumnCount();
        table = document.createTable(1, colcount + 1);
        rowtable = table.getRow(0);
        index = 0;
        row.add("No.");
        for (int i = 0; i < colcount; i++){
            row.add(durtable.getColumnName(i));
        }
        for (Iterator<String> it = row.iterator(); it.hasNext();) {
            String string = it.next();
            rowtable.getCell(index++).setText(string);
        }
        index = 0;
        row.clear();
        for (int i  = 0; i < rowcount; i++){
            row.add(""+(i+1));
            for (int j = 0; j < colcount; j++){
                row.add(durtable.getValueAt(i, j).toString());
            }
            rowtable = table.createRow();
            for (Iterator<String> it = row.iterator(); it.hasNext();) {
                String string = it.next();
                rowtable.getCell(index++).setText(string);
            }
            index = 0;
            row.clear();
        }
        
//        Frequency Summary
        paragraph1 = document.createParagraph();
        paragraph1run = paragraph1.createRun();
        paragraph1run.addBreak();
        paragraph1run.setText("Frequency Summary");
        rowcount = freqtable.getRowCount();
        colcount = freqtable.getColumnCount();
        table = document.createTable(1, colcount + 1);
        rowtable = table.getRow(0);
        index = 0;
        row.add("No.");
        for (int i = 0; i < colcount; i++){
            row.add(freqtable.getColumnName(i));
        }
        for (Iterator<String> it = row.iterator(); it.hasNext();) {
            String string = it.next();
            rowtable.getCell(index++).setText(string);
        }
        index = 0;
        row.clear();
        for (int i  = 0; i < rowcount; i++){
            row.add(""+(i+1));
            for (int j = 0; j < colcount; j++){
                row.add(freqtable.getValueAt(i, j).toString());
            }
            rowtable = table.createRow();
            for (Iterator<String> it = row.iterator(); it.hasNext();) {
                String string = it.next();
                rowtable.getCell(index++).setText(string);
            }
            index = 0;
            row.clear();
        }
        
//        Percentage Cost Summary
        paragraph1 = document.createParagraph();
        paragraph1run = paragraph1.createRun();
        paragraph1run.addBreak();
        paragraph1run.setText("Percentage Cost Summary");
        rowcount = percentcosttable.getRowCount();
        colcount = percentcosttable.getColumnCount();
        table = document.createTable(1, colcount + 1);
        rowtable = table.getRow(0);
        index = 0;
        row.add("No.");
        for (int i = 0; i < colcount; i++){
            row.add(percentcosttable.getColumnName(i));
        }
        for (Iterator<String> it = row.iterator(); it.hasNext();) {
            String string = it.next();
            rowtable.getCell(index++).setText(string);
        }
        index = 0;
        row.clear();
        for (int i  = 0; i < rowcount; i++){
            row.add(""+(i+1));
            for (int j = 0; j < colcount; j++){
                row.add(percentcosttable.getValueAt(i, j).toString());
            }
            rowtable = table.createRow();
            for (Iterator<String> it = row.iterator(); it.hasNext();) {
                String string = it.next();
                rowtable.getCell(index++).setText(string);
            }
            index = 0;
            row.clear();
        }
        
//        Percentage Duration Summary
        paragraph1 = document.createParagraph();
        paragraph1run = paragraph1.createRun();
        paragraph1run.addBreak();
        paragraph1run.setText("Percentage Duration Summary");
        rowcount = percentdurtable.getRowCount();
        colcount = percentdurtable.getColumnCount();
        table = document.createTable(1, colcount + 1);
        rowtable = table.getRow(0);
        index = 0;
        row.add("No.");
        for (int i = 0; i < colcount; i++){
            row.add(percentdurtable.getColumnName(i));
        }
        for (Iterator<String> it = row.iterator(); it.hasNext();) {
            String string = it.next();
            rowtable.getCell(index++).setText(string);
        }
        index = 0;
        row.clear();
        for (int i  = 0; i < rowcount; i++){
            row.add(""+(i+1));
            for (int j = 0; j < colcount; j++){
                row.add(percentdurtable.getValueAt(i, j).toString());
            }
            rowtable = table.createRow();
            for (Iterator<String> it = row.iterator(); it.hasNext();) {
                String string = it.next();
                rowtable.getCell(index++).setText(string);
            }
            index = 0;
            row.clear();
        }
        
//        Percentage Frequency Summary
        paragraph1 = document.createParagraph();
        paragraph1run = paragraph1.createRun();
        paragraph1run.addBreak();
        paragraph1run.setText("Percentage Frequency Summary");
        rowcount = percentfreqtable.getRowCount();
        colcount = percentfreqtable.getColumnCount();
        table = document.createTable(1, colcount + 1);
        rowtable = table.getRow(0);
        index = 0;
        row.add("No.");
        for (int i = 0; i < colcount; i++){
            row.add(percentfreqtable.getColumnName(i));
        }
        for (Iterator<String> it = row.iterator(); it.hasNext();) {
            String string = it.next();
            rowtable.getCell(index++).setText(string);
        }
        index = 0;
        row.clear();
        for (int i  = 0; i < rowcount; i++){
            row.add(""+(i+1));
            for (int j = 0; j < colcount; j++){
                row.add(percentfreqtable.getValueAt(i, j).toString());
            }
            rowtable = table.createRow();
            for (Iterator<String> it = row.iterator(); it.hasNext();) {
                String string = it.next();
                rowtable.getCell(index++).setText(string);
            }
            index = 0;
            row.clear();
        }
        
        FileOutputStream outputStream = null;
        try {
            outputStream = new FileOutputStream(filename);
        } catch (FileNotFoundException ex) {
            Logger.getLogger(ReportFrame.class.getName()).log(Level.SEVERE, null, ex);
        }
        try {
            document.write(outputStream);
            outputStream.close();
        } catch (IOException ex) {
            Logger.getLogger(ReportFrame.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    private void saveToPdf(String filename){
        try {
            Document document = new Document(new Rectangle(1024, 976));
            FileOutputStream outputStream = null;
            outputStream = new FileOutputStream(filename);
            PdfWriter.getInstance(document, outputStream);
            document.open();
            PdfPTable table;
            Paragraph paragraph;
            ArrayList<String> row = new ArrayList<String>();
        
            //        all Report
            paragraph = new Paragraph("All Report");
            document.add(paragraph);
            int rowcount = alltable.getRowCount();
            int colcount = alltable.getColumnCount();
            table = new PdfPTable(colcount + 1);
            row.add("No.");
            for (int i = 0; i < colcount; i++){
                row.add(alltable.getColumnName(i));
            }
            for (Iterator<String> it = row.iterator(); it.hasNext();) {
                String string = it.next();
                table.addCell(string);
            }
            row.clear();
            for (int i  = 0; i < rowcount; i++){
                row.add(""+(i+1));
                for (int j = 0; j < colcount; j++){
                    row.add(alltable.getValueAt(i, j).toString());
                }
                for (Iterator<String> it = row.iterator(); it.hasNext();) {
                    String string = it.next();
                    table.addCell(string);
                }
                row.clear();
            }
            document.add(table);
            paragraph = new Paragraph("\n"); 
            document.add(paragraph);
//        Cost Summary
            paragraph = new Paragraph("Cost Summary");
            document.add(paragraph);
            rowcount = costtable.getRowCount();
            colcount = costtable.getColumnCount();
            table = new PdfPTable(colcount + 1);
            row.add("No.");
            for (int i = 0; i < colcount; i++){
                row.add(costtable.getColumnName(i));
            }
            for (Iterator<String> it = row.iterator(); it.hasNext();) {
                String string = it.next();
                table.addCell(string);
            }
            row.clear();
            for (int i  = 0; i < rowcount; i++){
                row.add(""+(i+1));
                for (int j = 0; j < colcount; j++){
                    row.add(costtable.getValueAt(i, j).toString());
                }
                for (Iterator<String> it = row.iterator(); it.hasNext();) {
                    String string = it.next();
                    table.addCell(string);
                }
                row.clear();
            }
            document.add(table);
            paragraph = new Paragraph("\n"); 
            document.add(paragraph);

    //        Duration Summary
            paragraph = new Paragraph("Duration Summary");
            document.add(paragraph);
            rowcount = durtable.getRowCount();
            colcount = durtable.getColumnCount();
            table = new PdfPTable(colcount + 1);
            row.add("No.");
            for (int i = 0; i < colcount; i++){
                row.add(durtable.getColumnName(i));
            }
            for (Iterator<String> it = row.iterator(); it.hasNext();) {
                String string = it.next();
                table.addCell(string);
            }
            row.clear();
            for (int i  = 0; i < rowcount; i++){
                row.add(""+(i+1));
                for (int j = 0; j < colcount; j++){
                    row.add(durtable.getValueAt(i, j).toString());
                }
                for (Iterator<String> it = row.iterator(); it.hasNext();) {
                    String string = it.next();
                    table.addCell(string);
                }
                row.clear();
            }
            document.add(table);
            paragraph = new Paragraph("\n"); 
            document.add(paragraph);

    //        Frequency Summary
            paragraph = new Paragraph("Frequency Summary");
            document.add(paragraph);
            rowcount = freqtable.getRowCount();
            colcount = freqtable.getColumnCount();
            table = new PdfPTable(colcount + 1);
            row.add("No.");
            for (int i = 0; i < colcount; i++){
                row.add(freqtable.getColumnName(i));
            }
            for (Iterator<String> it = row.iterator(); it.hasNext();) {
                String string = it.next();
                table.addCell(string);
            }
            row.clear();
            for (int i  = 0; i < rowcount; i++){
                row.add(""+(i+1));
                for (int j = 0; j < colcount; j++){
                    row.add(freqtable.getValueAt(i, j).toString());
                }
                for (Iterator<String> it = row.iterator(); it.hasNext();) {
                    String string = it.next();
                    table.addCell(string);
                }
                row.clear();
            }
            document.add(table);
            paragraph = new Paragraph("\n"); 
            document.add(paragraph);

    //        Percentage Cost Summary
            paragraph = new Paragraph("Percentage Cost Summary");
            document.add(paragraph);
            rowcount = percentcosttable.getRowCount();
            colcount = percentcosttable.getColumnCount();
            table = new PdfPTable(colcount + 1);
            row.add("No.");
            for (int i = 0; i < colcount; i++){
                row.add(percentcosttable.getColumnName(i));
            }
            for (Iterator<String> it = row.iterator(); it.hasNext();) {
                String string = it.next();
                table.addCell(string);
            }
            row.clear();
            for (int i  = 0; i < rowcount; i++){
                row.add(""+(i+1));
                for (int j = 0; j < colcount; j++){
                    row.add(percentcosttable.getValueAt(i, j).toString());
                }
                for (Iterator<String> it = row.iterator(); it.hasNext();) {
                    String string = it.next();
                    table.addCell(string);
                }
                row.clear();
            }
            document.add(table);
            paragraph = new Paragraph("\n"); 
            document.add(paragraph);

//          Percentage Duration Summary
            paragraph = new Paragraph("Percentage Duration Summary");
            document.add(paragraph);
            rowcount = percentdurtable.getRowCount();
            colcount = percentdurtable.getColumnCount();
            table = new PdfPTable(colcount + 1);
            row.add("No.");
            for (int i = 0; i < colcount; i++){
                row.add(percentdurtable.getColumnName(i));
            }
            for (Iterator<String> it = row.iterator(); it.hasNext();) {
                String string = it.next();
                table.addCell(string);
            }
            row.clear();
            for (int i  = 0; i < rowcount; i++){
                row.add(""+(i+1));
                for (int j = 0; j < colcount; j++){
                    row.add(percentdurtable.getValueAt(i, j).toString());
                }
                for (Iterator<String> it = row.iterator(); it.hasNext();) {
                    String string = it.next();
                    table.addCell(string);
                }
                row.clear();
            }
            document.add(table);
            paragraph = new Paragraph("\n"); 
            document.add(paragraph);

    //        Percentage Frequency Summary
            paragraph = new Paragraph("Percentage Frequency Summary");
            document.add(paragraph);
            rowcount = percentfreqtable.getRowCount();
            colcount = percentfreqtable.getColumnCount();
            table = new PdfPTable(colcount + 1);
            row.add("No.");
            for (int i = 0; i < colcount; i++){
                row.add(percentfreqtable.getColumnName(i));
            }
            for (Iterator<String> it = row.iterator(); it.hasNext();) {
                String string = it.next();
                table.addCell(string);
            }
            row.clear();
            for (int i  = 0; i < rowcount; i++){
                row.add(""+(i+1));
                for (int j = 0; j < colcount; j++){
                    row.add(percentfreqtable.getValueAt(i, j).toString());
                }
                for (Iterator<String> it = row.iterator(); it.hasNext();) {
                    String string = it.next();
                    table.addCell(string);
                }
                row.clear();
            }
            document.add(table);
            paragraph = new Paragraph("\n"); 
            document.add(paragraph);
            
            document.close();
            outputStream.close();
        } catch (IOException ex) {
            System.out.println(ex.getStackTrace());
        } catch (DocumentException ex) {
            System.out.println(ex.getStackTrace());
        }
    }
    public ExtentionUsernameRecord getExtUsername(String extention){
        for (Iterator it = arraylist.iterator(); it.hasNext();) {
            ExtentionUsernameRecord object = (ExtentionUsernameRecord)it.next();
            if (object.Extention.equals(extention)){
                return object;
            }
        }
        return null;
    }
    public String[] populateAllReportRow(OutgoingCallReport obj){
        SimpleDateFormat df = new SimpleDateFormat("dd-MM-yyyy");
        SimpleDateFormat tf = new SimpleDateFormat("HH:mm:ss");
        String[] retval;
        long cost = (obj.duration * obj.unit);
        HLRRecord hlr = getHLR(obj.calledNo);
        int index = -1;
        ExtentionUsernameRecord extuser = null;
        TrunkLineRecord trunkline = null;
        if (Option.ExtentionUsername == option){
             extuser = getExtUsername(""+obj.stn);
             index = arraylist.indexOf(extuser);
        }
            
        else{
            trunkline = getTrunkLine(""+obj.trk);
            index = arraylist.indexOf(trunkline);
        }
        ProcessedData pd = map.get(index);
        if (pd != null){
            if (hlr.Type.equals("Local PSTN")){
                pd.cost[0] += cost;
                pd.duration[0] += obj.duration;
                pd.frequency[0]++;
            } else if (hlr.Type.equals("Local GSM")){
                pd.cost[1] += cost;
                pd.duration[1] += obj.duration;
                pd.frequency[1]++;
            } else if (hlr.Type.equals("SLJJ PSTN")){
                pd.cost[2] += cost;
                pd.duration[2] += obj.duration;
                pd.frequency[2]++;
            } else if (hlr.Type.equals("SLJJ GSM")){
                pd.cost[3] += cost;
                pd.duration[3] += obj.duration;
                pd.frequency[3]++;
            } else if (hlr.Type.equals("SLI")){
                pd.cost[4] += cost;
                pd.duration[4] += obj.duration;
                pd.frequency[4]++;
            } else {
                pd.cost[5] += cost;
                pd.duration[5] += obj.duration;
                pd.frequency[5]++;
            }
            map.put(index, pd);
            
        }
        if (option == Option.ExtentionUsername)
            retval= new String[]{
                ""+obj.stn,
                extuser.Username,
                df.format(obj.date),
                tf.format(obj.time),
                ""+obj.trk,
                obj.calledNo,
                hlr.Location,
                ""+obj.duration,
                ""+cost
            };
        else
            retval= new String[]{
                ""+obj.trk,
                trunkline.Line,
                df.format(obj.date),
                tf.format(obj.time),
                obj.calledNo,
                hlr.Location,
                ""+obj.duration,
                ""+(obj.duration * obj.unit)
            };
        return retval;
    }
    public TrunkLineRecord getTrunkLine(String trunk){
        for (Iterator it = arraylist.iterator(); it.hasNext();) {
            TrunkLineRecord object = (TrunkLineRecord)it.next();
            if (object.Trunk.equals(trunk)){
                return object;
            }
        }
        return null;
    }
    private HLRRecord getHLR (String dNumber){
        ArrayList<HLRRecord> hLRRecords =  TableAccess.getHLRRecords();
        for (Iterator<HLRRecord> it = hLRRecords.iterator(); it.hasNext();) {
            HLRRecord hLRRecord = it.next();
            if (dNumber.startsWith(hLRRecord.HLR)){
                return hLRRecord;
            }
        }
        return new HLRRecord("", "", "", 0, 0, "");
    }
    private JScrollPane makeTable(JTable table, String title){
        JTable rowtable = new RowNumberTable(table);
        JScrollPane scpane = new JScrollPane();
        scpane.setRowHeaderView(rowtable);
        scpane.setCorner(JScrollPane.UPPER_LEFT_CORNER, rowtable.getTableHeader());
        scpane.setName(title);
        scpane.setViewportView(table);
        scpane.setSize(scpane.getPreferredSize());
        return scpane;
    }
    private ArrayList<OutgoingCallReport> getFilteredoutGoOutgoingCallReports(ArrayList<OutgoingCallReport> reportscore){
        ArrayList<OutgoingCallReport> reports = new ArrayList<OutgoingCallReport>(reportscore);
        if (option == Option.ExtentionUsername){
            for (Iterator<OutgoingCallReport> it = reports.iterator(); it.hasNext();) {
                OutgoingCallReport outgoingCallReport = it.next();
                boolean exist = false;
                for (Iterator<ExtentionUsernameRecord> it1 = this.arraylist.iterator(); it1.hasNext();) {
                    ExtentionUsernameRecord extname = it1.next();
                    if ((""+outgoingCallReport.stn).equals(extname.Extention)){
                        Date time = outgoingCallReport.date;
                        time.setHours(outgoingCallReport.time.getHours());
                        time.setMinutes(outgoingCallReport.time.getMinutes());
                        time.setSeconds(outgoingCallReport.time.getSeconds());
                        long ltime = time.getTime();
                        System.out.println("-------------------");
                        System.out.println(starttime);
                        System.out.println(ltime);
                        System.out.println(endttime);
                        if (endttime > 0 && (starttime < endttime)){
                            if ((ltime) > starttime && (ltime) < endttime && outgoingCallReport.duration > durtime ){
                                exist = true;
                            }
                        }
                        else
                            exist = true;
                    }
                    
                }
                if (!exist){
                    it.remove();
                }
            }
        }
        else {
            for (Iterator<OutgoingCallReport> it = reports.iterator(); it.hasNext();) {
                OutgoingCallReport outgoingCallReport = it.next();
                boolean exist = false;
                for (Iterator<TrunkLineRecord> it1 = this.arraylist.iterator(); it1.hasNext();) {
                    TrunkLineRecord trunkline = it1.next();
                    if ((""+outgoingCallReport.trk).equals(trunkline.Trunk))
                        if (endttime > 0 && 
                                (starttime < endttime) && 
                                (outgoingCallReport.date.getTime() + outgoingCallReport.time.getTime()) > starttime &&
                                (outgoingCallReport.date.getTime() + outgoingCallReport.time.getTime()) < endttime &&
                                outgoingCallReport.duration > durtime
                                ){
                            exist = true;
                        } else
                            exist = true;
                }
                if (!exist){
                    it.remove();
                }
            }
        }
        return reports;
    }
    
}